﻿Imports System.Net
Imports System.Threading
Imports Sy.Data
Imports Sy.UI.Common
Imports System.IO
Imports System.Text

Public Class Form5
    Dim iii As Integer = 0
    Dim sc As Thread
    Dim AllPath As New Concurrent.ConcurrentQueue(Of TaskPathArg)
    Dim TaskMux As New Mutex
    Dim isfg As Boolean
    Dim newpath As String
    Dim isgw As Boolean
    Dim zdgw As Boolean
    Dim zdtype As String
    Dim gwvalue As Integer
    Dim isbg As Boolean
    Dim isfy As Boolean
    Dim sorclangs As String
    Dim translan As String
    Dim alloldpath As New List(Of String)
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        FolderBrowserDialog1.ShowDialog()
        imgpath.Text = FolderBrowserDialog1.SelectedPath
        GetAllFiles(imgpath.Text)
    End Sub

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        GetAllFiles(imgpath.Text)
    End Sub
    Private Sub GetAllFiles(ByVal strDirect As String)  '搜索所有目录下的文件
        iii = ListView1.Items.Count + 1
        If strDirect <> "" Then
            Dim mFileInfo As System.IO.FileInfo
            Dim mDir As System.IO.DirectoryInfo
            Dim mDirInfo As New System.IO.DirectoryInfo(strDirect)
            Try

                For Each mFileInfo In mDirInfo.GetFiles("*.*")
                    Dim ext = mFileInfo.Extension
                    Dim imgWidth As Integer
                    Dim imgHeight As Integer
                    Dim imglenth As String
                    If ext.ToLower = ".png" Or ext.ToLower = ".bmp" Or ext.ToLower = ".jpg" Or ext.ToLower = ".gif" Or ext.ToLower = ".jpeg" Or ext.ToLower = ".webp" Then
                        'Console.WriteLine(mFileInfo.FullName)
                        'Console.WriteLine(mFileInfo.Length)
                        'Console.WriteLine(mFileInfo.LastWriteTime)
                        'If InStr(alloldpath, mFileInfo.FullName) <= 0 .c Then
                        If alloldpath.Contains(mFileInfo.FullName) = False Then
                            alloldpath.Add(mFileInfo.FullName)
                            Dim imgPhoto As System.Drawing.Image = Imgresize(mFileInfo.FullName, 0, 0)
                            If imgPhoto IsNot Nothing Then
                                imgWidth = imgPhoto.Width
                                imgHeight = imgPhoto.Height
                                imgPhoto.Dispose()
                                imglenth = nFormatFileSize(mFileInfo.Length)
                                Dim itm As ListViewItem = ListView1.Items.Add(iii)
                                itm.SubItems.AddRange({CStr(mFileInfo.Name), CStr(mFileInfo.FullName), imglenth, CStr(imgWidth & " X " & imgHeight), CStr("未处理"), CStr("未处理"), CStr("未处理"), "", "", CStr(mFileInfo.LastWriteTime)})
                                iii = iii + 1
                                Dim t As New TaskList8
                                t.filename = mFileInfo.Name
                                t.imgpath = mFileInfo.FullName
                                t.imgfilesize = imglenth
                                t.imgsize = imgWidth & " X " & imgHeight
                                t.imgsizestate = "未处理"
                                t.koutustate = "未处理"
                                t.fanyistate = "未处理"
                                t.lastedittime = mFileInfo.LastWriteTime
                                t.Add()
                            End If
                        End If
                    End If
                Next
                For Each mDir In mDirInfo.GetDirectories
                    'Debug.Print("******目录回调*******")
                    GetAllFiles(mDir.FullName)
                Next
                Loadlist("")
            Catch ex As System.IO.DirectoryNotFoundException
                MsgBox("目录没找到：" + ex.Message)
            End Try
        End If
    End Sub
    Function nFormatFileSize(ByVal FileSize As Decimal, Optional ByVal DecimalDigits As Byte = 1) As String
        Try
            If FileSize = 0 Then Return "0"
            If FileSize >= 1024 Then
                Dim Power As Integer = Math.Min(Math.Floor(Math.Log(Math.Ceiling(Math.Abs(FileSize)), 1024)), 4)
                Dim Str As String = New String() {"KB", "MB", "GB", "TB"}(Power - 1)
                Return Format(FileSize / (1024 ^ Power), "#." & StrDup(DecimalDigits, "0")) & " " & Str
            Else
                Return "0" & Format(FileSize / (1024), "#." & StrDup(DecimalDigits, "0")) & " KB"
            End If
        Catch ex As Exception
            Return ""
        End Try
    End Function

    Private Sub ListView1_MouseUp(sender As Object, e As MouseEventArgs) Handles ListView1.MouseUp
        Try
            If e.Button = MouseButtons.Left Then
                If ListView1.SelectedItems.Count > 0 Then
                    'Dim SImg As Drawing.Image = Drawing.Image.FromFile(ListView1.SelectedItems.Item(0).SubItems(2).Text), Bmp As Drawing.Bitmap
                    'Bmp = New Drawing.Bitmap(100, 100)
                    'Dim g As Drawing.Graphics = Drawing.Graphics.FromImage(Bmp) : g.Clear(Drawing.Color.White)
                    'g.DrawImage(SImg, New Drawing.RectangleF(0, 0, 100, 100))
                    'SImg.Dispose()
                    Dim filePath = ListView1.SelectedItems.Item(0).SubItems(2).Text
                    Dim filePath2 = ListView1.SelectedItems.Item(0).SubItems(9).Text
                    If IO.File.Exists(filePath) Then
                        PictureBox1.Image = Imgresize(filePath, 300, 300)
                        If e.Y > Me.Height - 300 Then
                            PictureBox1.Location = New Point(PictureBox1.Left, e.Y - 300)
                        Else
                            PictureBox1.Location = New Point(PictureBox1.Left, e.Y)
                        End If
                        PictureBox1.Show()
                    Else
                        PictureBox1.Hide()
                    End If
                    If IO.File.Exists(filePath2) Then
                        PictureBox2.Image = Imgresize(filePath2, 300, 300)
                        If e.Y > Me.Height - 300 Then
                            PictureBox2.Location = New Point(PictureBox2.Left, e.Y - 300)
                        Else
                            PictureBox2.Location = New Point(PictureBox2.Left, e.Y)
                        End If
                        PictureBox2.Show()
                    Else
                        PictureBox2.Hide()
                    End If
                    Exit Sub
                End If
                PictureBox1.BackgroundImage = Nothing
                PictureBox1.Hide()
                PictureBox2.BackgroundImage = Nothing
                PictureBox2.Hide()
            Else
                Me.ContextMenuStrip1.Show(Me, PointToClient(Cursor.Position))
            End If
        Catch ex As Exception
            MsgBox(ex.ToString)
        End Try

    End Sub


    Private Sub Form5_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Try
            loadlan(lang, 0)
            loadlan(sorclan, 1)
            Dim urls = "https://www.miwaimao.com/api/getamount.php?user_name=" & UserNamelo
            Dim Resa = Sy.Net.Factory.Http(urls).Get()
            Dim userinfo = Split(Resa, "|||")
            is_vip = userinfo(1)
            If is_vip = "Yes" Then
                Label4.Text = "当前账户为包年包月版本"
                amount = 0
            Else
                Label4.Text = "当前账户余额：" & userinfo(0)
                amount = CDec(userinfo(0))
            End If
            zhidingtype.Items.Add("宽度")
            zhidingtype.Items.Add("高度")
            zhidingtype.SelectedIndex = 0
            PictureBox2.BringToFront()
            PictureBox1.BringToFront()
            Dim Create = CreateSQLBuilder(Of TaskList8).CreateSQL()
            DB8 = New SQLite(Create, Application.StartupPath & "\Config\task8.db")
            TaskList8.AddDB(DB8)
            UIAdapter.ListviewAdapter(Of TaskList8)(ListView1, "序号")
            Loadlist("")
            Dim stlitten = New System.Threading.Thread(New System.Threading.ParameterizedThreadStart(AddressOf Listen))
            stlitten.Name = NameOf(Listen)
            stlitten.Start()   '启动线程
        Catch ex As Exception
            MsgBox("载入出错！")
        End Try
    End Sub
    Sub Loadlist(sqlstr As String)
        Try
            With ListView1
                .Items.Clear()
            End With
            Dim TaskLists = If(sqlstr.IsNotWhiteSpace, TaskList8.LoadWhere(sqlstr), TaskList8.Load())
            Dim i As Long = 1
            For Each TaskList In TaskLists
                Dim a = UIAdapter.GetListViewItem(TaskList, i)
                Dim itm As ListViewItem = ListView1.Items.Add(a) '状态 进度 id
                itm.Tag = TaskList
                i = i + 1
            Next
        Catch ex As Exception
            MsgBox("加载数据异常", MsgBoxStyle.OkOnly, "提示")
        End Try
    End Sub
    Sub loadlan(opt As ComboBox, index As Integer)
        opt.Items.Add("英语")
        opt.Items.Add("简体中文")
        opt.Items.Add("繁体中文")
        opt.Items.Add("法语")
        opt.Items.Add("西班牙语")
        opt.Items.Add("德语")
        opt.Items.Add("意大利语")
        opt.Items.Add("波兰语")
        opt.Items.Add("荷兰语")
        opt.Items.Add("日本语")
        opt.Items.Add("俄语")
        opt.Items.Add("泰语")
        opt.Items.Add("他加禄语(菲律宾)")
        opt.Items.Add("越南语")
        opt.Items.Add("土耳其语")
        opt.Items.Add("阿拉伯语")
        opt.Items.Add("印尼语")
        opt.Items.Add("韩语")
        opt.Items.Add("葡萄牙语(巴西)")
        opt.Items.Add("马来语")
        opt.Items.Add("捷克语")
        opt.Items.Add("爪哇语")
        opt.Items.Add("罗马尼亚语")
        opt.Items.Add("缅甸语")
        opt.Items.Add("匈牙利语")
        opt.SelectedIndex = index
    End Sub
    Function getlancode(TargetLanguage As String)
        Try
            Select Case TargetLanguage
                Case "英语"
                    Return "ENG"
                Case "繁体中文"
                    Return "CHT"
                Case "法语"
                    Return "FRA"
                Case "西班牙语"
                    Return "ESP"
                Case "德语"
                    Return "DEU"
                Case "意大利语"
                    Return "ITA"
                Case "波兰语"
                    Return "PLK"
                Case "荷兰语"
                    Return "NLD"
                Case "日本语"
                    Return "JPN"
                Case "俄语"
                    Return "RUS"
                Case "泰语"
                    Return "TH"
                Case "他加禄语(菲律宾)"
                    Return "TL"
                Case "越南语"
                    Return "VIN"
                Case "土耳其语"
                    Return "TRK"
                Case "阿拉伯语"
                    Return "AR"
                Case "印尼语"
                    Return "ID"
                Case "韩语"
                    Return "KOR"
                Case "简体中文"
                    Return "CHS"
                Case "捷克语"
                    Return "CSY"
                Case "匈牙利语"
                    Return "HUN"
                Case "爪哇语"
                    Return "JW"
                Case "葡萄牙语(巴西)"
                    Return "PTB"
                Case "缅甸语"
                    Return "MY"
                Case "罗马尼亚语"
                    Return "ROM"
                Case "马来语"
                    Return "MS"
            End Select
        Catch ex As Exception
            Return ""
        End Try
    End Function
    Function Imgresize(ByVal ImgPath As String, Optional ByVal MaxHeight As Integer = 0, Optional ByVal MaxWidth As Integer = 0) As Drawing.Bitmap
        Try
            'Dim fname = Path.GetFileName(ImgPath)
            Dim SImg As Drawing.Image, Bmp As Drawing.Bitmap, scale As Decimal
            Dim fname As New System.IO.FileInfo(ImgPath)
            If fname.Extension.ToLower = ".webp" Then
                Dim bs As Byte() = IO.File.ReadAllBytes(ImgPath)
                SImg = Imazen.WebP.SimpleDecoder.DecodeFromBytes(bs, bs.Length)
            Else
                SImg = Drawing.Image.FromFile(ImgPath)
            End If
            Dim nw As Integer
            Dim nh As Integer
            scale = SImg.Height / SImg.Width
            If MaxHeight = 0 And MaxWidth <> 0 Then
                nw = MaxWidth
                nh = CInt(nw * scale)
            End If
            If MaxHeight <> 0 And MaxWidth <> 0 Then
                If SImg.Height > SImg.Width Then
                    nh = MaxHeight
                    nw = CInt(MaxHeight / scale)
                Else
                    nw = MaxWidth
                    nh = CInt(nw * scale)
                End If
            End If
            If MaxHeight <> 0 And MaxWidth = 0 Then
                nh = MaxHeight
                nw = CInt(MaxHeight / scale)
            End If
            If MaxHeight = 0 And MaxWidth = 0 Then
                nh = SImg.Height
                nw = SImg.Width
            End If
            Bmp = New Drawing.Bitmap(nw, nh)
            Dim g As Drawing.Graphics = Drawing.Graphics.FromImage(Bmp) : g.Clear(Drawing.Color.White)
            g.DrawImage(SImg, New Drawing.RectangleF(0, 0, nw, nh))
            SImg.Dispose()
            Return Bmp
        Catch ex As Exception
            Return Nothing
        End Try
        'Console.WriteLine(nh & ":" & nw)
    End Function

    Private Sub ListView1_LostFocus(sender As Object, e As EventArgs) Handles ListView1.LostFocus
        PictureBox1.BackgroundImage = Nothing
        PictureBox1.Hide()
        PictureBox2.BackgroundImage = Nothing
        PictureBox2.Hide()
    End Sub

    Private Sub CheckBox1_CheckedChanged(sender As Object, e As EventArgs) Handles CheckBox1.CheckedChanged
        Try
            If CheckBox1.Checked = True Then
                For i = 0 To ListView1.Items.Count - 1
                    ListView1.Items(i).Checked = True
                Next
            Else
                For i = 0 To ListView1.Items.Count - 1
                    ListView1.Items(i).Checked = False
                Next
            End If
        Catch ex As Exception
            MsgBox("勾选出错！")
        End Try
    End Sub

    Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
        Dim TaskList As TaskList8
        TaskList.Execute("delete from t_TaskList8 where 1=1")
        ListView1.Items.Clear()
        alloldpath.Clear()
        Loadlist("")
    End Sub

    Private Sub Button5_Click(sender As Object, e As EventArgs) Handles Button5.Click
        For Each i As ListViewItem In ListView1.CheckedItems
            Dim TaskList As TaskList8 = i.Tag
            TaskList.Del()
            ListView1.Items.Remove(i)
            alloldpath.Remove(i.SubItems(2).Text)
        Next
        Loadlist("")
    End Sub

    Private Sub Button3_Click(sender As Object, e As EventArgs) Handles btnexport.Click
        FolderBrowserDialog1.ShowDialog()
        export.Text = FolderBrowserDialog1.SelectedPath
    End Sub

    Private Sub isfugai_CheckedChanged(sender As Object, e As EventArgs) Handles isfugai.CheckedChanged
        If isfugai.Checked Then
            export.Enabled = False
            btnexport.Enabled = False
        Else
            export.Enabled = True
            btnexport.Enabled = True
        End If
    End Sub

    Private Sub shuchu_TextChanged(sender As Object, e As EventArgs) Handles shuchu.TextChanged
        Try
            If UBound(Split(shuchu.Text, vbCrLf)) > 9 Then
                shuchu.Text = Mid(shuchu.Text, InStr(shuchu.Text, vbCrLf) + 2)
            End If
            shuchu.SelectionStart = Len(shuchu.Text)
            shuchu.ScrollToCaret()
        Catch ex As Exception
            MsgBox("状态输出异常！", MsgBoxStyle.OkOnly, "提示")
        End Try
    End Sub

    Private Sub istrans_CheckedChanged(sender As Object, e As EventArgs) Handles istrans.CheckedChanged
        If istrans.Checked Then
            lang.Enabled = True
            sorclan.Enabled = True
        Else
            lang.Enabled = False
            sorclan.Enabled = False
        End If
    End Sub

    Private Sub isgrow_CheckedChanged(sender As Object, e As EventArgs) Handles isgrow.CheckedChanged
        If isgrow.Checked Then
            withorheight.Enabled = True
            zhiding.Checked = False
        ElseIf zhiding.Checked = False Then
            withorheight.Enabled = False
        End If
    End Sub

    Private Sub btnstart_Click(sender As Object, e As EventArgs) Handles btnstart.Click
        If isfugai.Checked = False And System.IO.Directory.Exists(export.Text) = False Then
            MsgBox("请先至少选择一个存放图片有效路径！", MsgBoxStyle.OkOnly, "提示")
            Exit Sub
        End If
        AllPath = New Concurrent.ConcurrentQueue(Of TaskPathArg)
        isfg = isfugai.Checked
        newpath = export.Text
        isgw = isgrow.Checked
        zdgw = zhiding.Checked
        zdtype = zhidingtype.Text
        gwvalue = withorheight.Value
        isbg = isremovebg.Checked
        isfy = istrans.Checked
        translan = lang.Text
        sorclangs = sorclan.Text
        btnstart.Enabled = False
        btnstop.Enabled = True
        For i = 0 To ListView1.Items.Count - 1
            Dim LtvItem = ListView1.Items(i)
            If LtvItem.Checked Then
                Dim npath = LtvItem.SubItems(2).Text
                AllPath.Enqueue(New TaskPathArg(LtvItem, npath))
                'Dim imgPhoto As System.Drawing.Image = System.Drawing.Image.FromFile(npath)
                'If isgrow.Checked Then
                '    Dim Bmp As Drawing.Bitmap = Imgresize(npath, withorheight.Value, withorheight.Value)
                '    Bmp.Save(npath)
                '    Bmp.Dispose()
                'End If
            End If
        Next
        sc = New System.Threading.Thread(New System.Threading.ParameterizedThreadStart(AddressOf shengcheng))
        sc.Start()
    End Sub
    Sub shengcheng()
        Try
            Do
                Dim dealsize As String = "未处理"
                Dim dealbg As String = "未处理"
                Dim dealfy As String = "未处理"
                Dim je As Double = 0
                Dim TaskPathArg As TaskPathArg
                If AllPath.TryDequeue(TaskPathArg) Then
                    Dim DBOBJ = TaskPathArg.DBOBJ, HasChange As Boolean = False
                    Dim UI_ListViewItem = TaskPathArg.Item
                    Dim realpath = TaskPathArg.Value
                    Dim RequestId As String

                    If System.IO.File.Exists(realpath) = True Then
                        'Dim fname = Path.GetFileName(realpath)
                        Dim fname As New System.IO.FileInfo(realpath)
                        Dim Bmp As Drawing.Bitmap
                        Bmp = Imgresize(realpath, 0, 0)
                        '修改大小
                        If isgw = True Then
                            Bmp = Imgresize(realpath, gwvalue, gwvalue)
                            dealsize = "已处理"
                            HasChange = True
                        End If
                        If zdgw = True Then
                            If zdtype = "高度" Then
                                Bmp = Imgresize(realpath, gwvalue, 0)
                                dealsize = "已处理"
                                HasChange = True
                            End If
                            If zdtype = "宽度" Then
                                Bmp = Imgresize(realpath, 0, gwvalue)
                                dealsize = "已处理"
                                HasChange = True
                            End If
                        End If
                        '抠图

                        Dim thetype = ""
                        Dim imgurl = ""

                        Dim USERKEY = "9964996788"
                        Dim ImgTransKey = "4336835733"
                        Dim ImgMattingKey = "2455484648"
                        If isbg AndAlso Bmp IsNot Nothing Then
                            If amount <= 0 And is_vip <> "Yes" Then
                                MsgBox("余额不足")
                                btnstart.Enabled = True
                                btnstop.Enabled = False
                                Exit Sub
                            End If
                            'Dim appcode = "2d72d998c0c642e9835d9fad8cb8039e"
                            'Dim url = "https://objseg.market.alicloudapi.com/commonseg/rgba"
                            'Dim imgbaseb4 = "data:image/png;base64," & IMG_TO_BASE64(Bmp)
                            'Dim formdata = "{""photo"": """ & imgbaseb4 & """}"
                            'Dim html = getnewhtml(url, "POST", formdata, "", "", "", "", "application/json; charset=UTF-8")

                            'Dim url = "https://picupapi.tukeli.net/api/v1/matting?mattingType=6"
                            'Dim APIKEY = "db379440fda943e895f4af2a50a55ebf"
                            'Using mem As New IO.MemoryStream
                            '    Bmp.Save(mem, Imaging.ImageFormat.Png)
                            '    Dim FileBin As Byte() = mem.ToArray()
                            '    Dim Res = Sy.Net.Factory.Http(url).SetHeader("APIKEY", APIKEY).SetPostDataBuilder(Sy.Net.PostDataBuilder.Add("file.png", FileBin, "file")).DownLoad()
                            '    'IO.File.WriteAllBytes(Sy.Environment.Path.Desktop("1.png"), Res)
                            '    Using ms1 As New IO.MemoryStream(Res)
                            '        Bmp = Imgtowhite(CType(Image.FromStream(ms1), Bitmap))
                            '    End Using
                            'End Using
                            Dim Action = "GetImageMatting"
                            Dim url = "http://api2.tosoiot.com/async-matting"
                            'Dim md5str = SourceLanguage & "_" & TargetLanguage & "_local_" & USERKEY & "_" & ImgTransKey
                            Dim CommitTime = GetTimeStamp(TimestampMode.UtcSecond)
                            Dim md5str = CommitTime & "_" & USERKEY & "_" & ImgMattingKey
                            Dim Sign = Sy.Security.MD5.Encrypt(md5str).ToLower
                            Dim Query = "Action=" & Action & "&CommitTime=" & CommitTime & "&ImgMattingKey=" & ImgMattingKey & "&Sign=" & Sign
                            'Dim sydata = Sy.Net.PostDataBuilder.Add("Action", Action).Add("CommitTime", CommitTime).Add("ImgMattingKey", ImgMattingKey).Add("Sign", Sign)

                            Using mem As New IO.MemoryStream
                                Bmp.Save(mem, Imaging.ImageFormat.Png)
                                Dim FileBin As Byte() = mem.ToArray()
                                'sydata.Add("file.png", FileBin, "file-stream")
                                Dim Res = Sy.Net.Factory.Http($"{url}?{Query}").SetData(Sy.Net.PostDataBuilder.Add("file.png", FileBin, "file-stream")).Post()
                                If InStr(Res, ",""SslUrl"":""") > 0 Then
                                    Dim imgurla = Split(Res, ",""SslUrl"":""")(1)
                                    imgurl = Split(imgurla, """}")(0)
                                    Dim RequestIda = Split(Res, "RequestId"":""")(1)
                                    RequestId = Split(RequestIda, """,")(0)
                                    DBOBJ.RequestId2 = RequestId : HasChange = True
                                    Sy.Net.Factory.Http(imgurl).SetAfterResponseWithStream(Function(r, p)
                                                                                               Bmp = New Bitmap(p)
                                                                                               Return ""
                                                                                           End Function).Get()
                                    DBOBJ.outpaths = $"{newpath}\{ fname.Name}" : HasChange = True
                                    dealbg = "已处理"
                                    thetype = "白底抠图"
                                    je = je + 0.1
                                Else
                                    dealbg = "抠图失败"
                                End If
                            End Using

                        End If
                        '图片翻译
                        If isfy = True AndAlso Bmp IsNot Nothing Then
                            If amount <= 0 And is_vip <> "Yes" Then
                                MsgBox("余额不足")
                                btnstart.Enabled = True
                                btnstop.Enabled = False
                                Exit Sub
                            End If
                            Dim url = "http://api2.tosoiot.com"
                            Dim Action = "GetImageTranslate"
                            Dim SourceLanguage = getlancode(sorclangs)
                            Dim filenames = GetTimeStamp() & ".png"
                            Dim TargetLanguage = getlancode(translan)

                            'Dim filebase64 = "data:image/png;base64," & IMG_TO_BASE64(Bmp)
                            Dim md5str = SourceLanguage & "_" & TargetLanguage & "_local_" & USERKEY & "_" & ImgTransKey
                            Dim Sign = Sy.Security.MD5.Encrypt(md5str).ToLower
                            'Dim postdata = Sy.Net.PostDataBuilder
                            'postdata.Add("file-base64", filebase64)

                            url = url & "/?Action=" & Action & "&SourceLanguage=" & SourceLanguage & "&TargetLanguage=" & TargetLanguage & "&Url=local&ImgTransKey=" & ImgTransKey & "&Sign=" & Sign
                            'Dim Res = Sy.Net.Factory.Http(url).SetPostDataBuilder(postdata).Post()
                            Using mem As New IO.MemoryStream
                                Bmp.Save(mem, Imaging.ImageFormat.Png)
                                Dim FileBin As Byte() = mem.ToArray()
                                Dim Res = Sy.Net.Factory.Http(url).SetPostDataBuilder(Sy.Net.PostDataBuilder.Add("file.png", FileBin, "file-stream")).Post()
                                If InStr(Res, "SslUrl"":""") > 0 Then
                                    Dim imgurla = Split(Res, "SslUrl"":""")(1)
                                    imgurl = Split(imgurla, """,")(0)
                                    Dim RequestIda = Split(Res, "RequestId"":""")(1)
                                    RequestId = Split(RequestIda, """,")(0)
                                    DBOBJ.RequestId = RequestId : HasChange = True
                                    Sy.Net.Factory.Http(imgurl).SetAfterResponseWithStream(Function(r, p)
                                                                                               Bmp = New Bitmap(p)
                                                                                               Return ""
                                                                                           End Function).Get()

                                    dealfy = "已翻译"
                                    thetype &= "图片翻译"
                                    je = je + 0.05
                                Else
                                    dealfy = "翻译失败"
                                End If
                            End Using
                        End If

                        '保存图片
                        If isfg = True Then
                            Saveimg(realpath, fname.Extension, Bmp)
                            DBOBJ.outpaths = realpath
                            HasChange = True
                            DBOBJ.fanyistate = dealfy
                            DBOBJ.koutustate = dealbg
                            DBOBJ.imgsizestate = dealsize
                            Dim mFileInfo As System.IO.FileInfo = New System.IO.FileInfo(realpath)
                            Dim imgPhoto As System.Drawing.Image = Imgresize(mFileInfo.FullName, 0, 0)
                            DBOBJ.imgsize = imgPhoto.Width & " X " & imgPhoto.Height
                            DBOBJ.imgfilesize = nFormatFileSize(mFileInfo.Length)

                            Invoke(Sub()
                                       UI_ListViewItem.SubItems(5).Text = dealsize
                                       UI_ListViewItem.SubItems(6).Text = dealbg
                                       UI_ListViewItem.SubItems(7).Text = dealfy
                                       UI_ListViewItem.SubItems(8).Text = RequestId
                                       UI_ListViewItem.SubItems(9).Text = realpath
                                       shuchu.Text &= realpath & " 处理成功" & vbCrLf
                                   End Sub)
                        Else
                            If System.IO.Directory.Exists(newpath) Then
                                Saveimg(newpath & "\" & fname.Name, fname.Extension, Bmp)
                                DBOBJ.outpaths = $"{newpath}\{ fname.Name}"
                                DBOBJ.fanyistate = dealfy
                                DBOBJ.koutustate = dealbg
                                DBOBJ.imgsizestate = dealsize
                                Dim mFileInfo As System.IO.FileInfo = New System.IO.FileInfo(newpath & "\" & fname.Name)
                                Dim imgPhoto As System.Drawing.Image = Imgresize(mFileInfo.FullName, 0, 0)
                                DBOBJ.imgsize = imgPhoto.Width & " X " & imgPhoto.Height
                                DBOBJ.imgfilesize = nFormatFileSize(mFileInfo.Length)
                                HasChange = True
                                Invoke(Sub()
                                           UI_ListViewItem.SubItems(5).Text = dealsize
                                           UI_ListViewItem.SubItems(6).Text = dealbg
                                           UI_ListViewItem.SubItems(7).Text = dealfy
                                           UI_ListViewItem.SubItems(8).Text = RequestId
                                           UI_ListViewItem.SubItems(9).Text = newpath & "\" & fname.Name
                                           shuchu.Text &= newpath & "\" & fname.Name & " 处理成功" & vbCrLf
                                       End Sub)
                            Else
                                Invoke(Sub()
                                           shuchu.Text &= newpath & " 目录不存在" & vbCrLf
                                       End Sub)
                            End If
                        End If

                        If HasChange Then DBOBJ.Edt()
                        If thetype <> "" Then
                            Dim postdatas = Sy.Net.PostDataBuilder
                            postdatas.Add("user_name", UserNamelo)
                            postdatas.Add("imgurl", Sy.Security.MD5.Encrypt(realpath))
                            postdatas.Add("thetype", thetype)
                            postdatas.Add("kje", je.ToString)
                            Dim urls = "https://www.miwaimao.com/api/imgtoolapi.php"
                            Dim Resa = Sy.Net.Factory.Http(urls).SetPostDataBuilder(postdatas).Post()
                            If Resa = "no" Or Resa = "err" Then
                                Invoke(Sub()
                                           btnstart.Enabled = True
                                           btnstop.Enabled = False
                                           shuchu.Text &= "所有任务已终止" & vbCrLf
                                           MsgBox("余额不足或出错，已停止！")
                                           Loadlist("")
                                       End Sub)
                                Exit Sub
                            End If
                        End If
                        Bmp.Dispose()
                    End If
                Else
                    Invoke(Sub()
                               btnstart.Enabled = True
                               btnstop.Enabled = False
                               shuchu.Text &= "所有任务已完成" & vbCrLf
                               MsgBox("已经完成！")
                               Loadlist("")
                           End Sub)
                    Exit Sub
                End If
            Loop
        Catch ex As Exception
            Console.WriteLine(ex.Message)
            Invoke(Sub()
                       btnstart.Enabled = True
                       btnstop.Enabled = False
                       shuchu.Text &= "所有任务已终止" & vbCrLf
                       MsgBox("已经停止！")
                   End Sub)
        End Try
    End Sub
    Function Imgtowhite(img As Bitmap) As Bitmap
        Try
            Dim Bmpss = New Drawing.Bitmap(img.Width, img.Height)
            Dim g As Drawing.Graphics = Drawing.Graphics.FromImage(Bmpss) : g.Clear(Drawing.Color.White)
            g.DrawImage(img, New Drawing.RectangleF(0, 0, img.Width, img.Height))
            Return Bmpss
        Catch ex As Exception
            Return Nothing
        End Try
    End Function
    Sub Saveimg(path As String, Extension As String, img As Drawing.Bitmap)
        Try
            Dim ext As Drawing.Imaging.ImageFormat
            If Extension.ToLower = ".png" Then
                ext = Drawing.Imaging.ImageFormat.Png
            End If
            If Extension.ToLower = ".gif" Then
                ext = Drawing.Imaging.ImageFormat.Gif
            End If
            If Extension.ToLower = ".jpg" Or Extension.ToLower = ".jpeg" Then
                ext = Drawing.Imaging.ImageFormat.Jpeg
            End If
            If Extension.ToLower = ".bmp" Then
                ext = Drawing.Imaging.ImageFormat.Bmp
            End If

            If Extension.ToLower = ".webp" Then
                Using bmp As New Bitmap(img.Width, img.Height, Imaging.PixelFormat.Format32bppArgb)
                    ' 将图片重绘到新画布
                    Using g As Graphics = Graphics.FromImage(bmp)
                        g.Clear(Color.White)
                        g.DrawImage(img, 0, 0, img.Width, img.Height)
                    End Using
                    ' 转码并保存文件
                    Using fs As IO.FileStream = IO.File.Create(path)
                        Imazen.WebP.SimpleEncoder.Encode(bmp, fs, 100)
                        ' 原版需要实例化
                        '(New Imazen.WebP.SimpleEncoder).Encode(bmp, fs, 100)
                    End Using
                End Using
            Else
                img = Imgtowhite(img)
                img.Save(path, ext)
            End If
        Catch ex As Exception
            Console.WriteLine(ex)
            'File.WriteAllText(Application.StartupPath & "\err.txt", ex.ToString)
        End Try
    End Sub
    Function IMG_TO_BASE64(IMG As Image) As String
        Try
            If IMG.IsNotNothing Then
                Dim MS As New IO.MemoryStream()
                Using BMP As New Bitmap(IMG)
                    BMP.Save(MS, Imaging.ImageFormat.Png)
                    Dim BYT As Byte() = MS.GetBuffer()
                    Dim Base64_Str As String = Convert.ToBase64String(BYT)
                    Return Base64_Str
                End Using
            Else
                Return ""
            End If
        Catch ex As Exception
            Return ex.Message
        End Try
    End Function

    Private Sub Button3_Click_1(sender As Object, e As EventArgs) Handles Button3.Click
        'Imgresize("C:\Users\Alienware\Desktop\新建文件夹\IMG_3403.PNG", 0, 1000)
        'Imgresize("C:\Users\Alienware\Desktop\新建文件夹\IMG_3403.PNG", 0, 0)
        'Imgresize("C:\Users\Alienware\Desktop\新建文件夹\IMG_3403.PNG", 1000, 0)
        Dim bs As Byte() = IO.File.ReadAllBytes("C:\Users\Alienware\Desktop\新建文件夹\bbbbbbbbb.webp")
        Dim img As Bitmap = Imazen.WebP.SimpleDecoder.DecodeFromBytes(bs, bs.Length)

        PictureBox1.Image = img
    End Sub

    Private Sub ListView1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListView1.SelectedIndexChanged

    End Sub

    Private Sub imgpath_TextChanged(sender As Object, e As EventArgs) Handles imgpath.TextChanged

    End Sub

    Private Sub imgpath_DragEnter(sender As Object, e As DragEventArgs) Handles imgpath.DragEnter
        If e.Data.GetDataPresent(DataFormats.FileDrop) Then
            e.Effect = DragDropEffects.Link
        Else
            e.Effect = DragDropEffects.None
        End If
    End Sub

    Private Sub imgpath_DragDrop(sender As Object, e As DragEventArgs) Handles imgpath.DragDrop
        'Console.WriteLine(e.Data.GetData(DataFormats.FileDrop)(0))
        imgpath.Text = System.IO.Directory.GetParent(e.Data.GetData(DataFormats.FileDrop)(0)).ToString
        GetAllFiles(imgpath.Text)
    End Sub

    Private Sub Button8_Click(sender As Object, e As EventArgs) Handles Button8.Click
        Try
            Dim urls = "https://www.miwaimao.com/api/getamount.php?user_name=" & UserNamelo
            Dim Resa = Sy.Net.Factory.Http(urls).Get()
            Dim userinfo = Split(Resa, "|||")
            is_vip = userinfo(1)
            If is_vip = "Yes" Then
                Label4.Text = "当前账户为包年包月版本"
                amount = 0
            Else
                Label4.Text = "当前账户余额：" & userinfo(0)
                amount = CDec(userinfo(0))
            End If
        Catch ex As Exception
            MsgBox("获取失败!")
        End Try
    End Sub

    Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
        Try
            Dim url = "https://www.miwaimao.com/softlogin.php?UserName=" & UserNamelo & "&Version=" & Version & "&step=2&logintime=" & logintime
            Console.WriteLine(url)
            Dim html = getnewhtml(url)
            Console.WriteLine(html)
            If html = "8" Then
                MsgBox("您的账户已在别处登录，当前会话退出！")
                Timer1.Enabled = False
                End
            End If
        Catch ex As Exception
            MsgBox("登录异常，当前会话退出！")
            Timer1.Enabled = False
            End
        End Try
    End Sub

    Private Sub Form5_Closed(sender As Object, e As EventArgs) Handles Me.Closed
        End
    End Sub
    Const Port As Integer = 5589
    Sub Listen()
        Try
            Dim listener = New HttpListener()
            listener.Start()
            'netsh http add urlacl url=http://+:5589/  user=Everyone
            'netsh advfirewall firewall Add rule name="命令行Web访问" dir=in protocol=tcp localport=5589 action=allow
            'pause
            listener.Prefixes.Add($"http://+:{Port}/")
            listener.Start()
            Do
                Dim Context = listener.GetContext()
                '为防止延迟点击采集导致的异常问题
                Dim url = Context.Request.QueryString.Get("url")
                Dim lstvid As Integer = CInt(Context.Request.QueryString.Get("lstvid"))

                Invoke(Sub()
                           Console.WriteLine(ListView1.Items(0).SubItems(9).Text)
                           Console.WriteLine(url)
                           Dim fname As New System.IO.FileInfo(ListView1.SelectedItems(0).SubItems(10).Text)
                           'File.WriteAllText(Application.StartupPath & "\err.txt", fname.ToString)
                           Dim Bmp As Drawing.Bitmap
                           Using mem As New IO.MemoryStream
                               'Bmp.Save(mem, Imaging.ImageFormat.Png)
                               If url <> "" Then
                                   Sy.Net.Factory.Http(url).SetAfterResponseWithStream(Function(r, p)
                                                                                           Bmp = New Bitmap(p)
                                                                                           Return ""
                                                                                       End Function).Get()
                                   Saveimg(ListView1.SelectedItems(0).SubItems(9).Text, fname.Extension, Bmp)
                               Else
                                   MsgBox("图片不存在")
                               End If
                           End Using
                       End Sub)
            Loop
        Catch ex As HttpListenerException
            MsgBox("请以管理员身份启用[HttpListenAuth.bat]脚本后重试")
        End Try
    End Sub

    Private Sub ListView1_DoubleClick(sender As Object, e As EventArgs) Handles ListView1.DoubleClick

    End Sub

    Private Sub Button6_Click(sender As Object, e As EventArgs) Handles Button6.Click
        Try
            Dim url = "https://www.miwaimao.com/checklogin.php?user_name=" & UserNamelo & "&user_pass=" & Userpasslo
            If IsNotWhiteSpace(url) Then
                System.Diagnostics.Process.Start(url)
            End If
        Catch ex As Exception
            MsgBox("打开出错!")
        End Try
    End Sub

    Private Sub btnstop_Click(sender As Object, e As EventArgs) Handles btnstop.Click
        Try
            If sc.IsAlive Then
                sc.Abort()
            End If
            btnstart.Enabled = True
            btnstop.Enabled = False
            shuchu.Text &= "已停止" & vbCrLf
            MsgBox("已停止!")
            Loadlist("")
        Catch ex As Exception

        End Try
    End Sub

    Private Sub zhiding_CheckedChanged(sender As Object, e As EventArgs) Handles zhiding.CheckedChanged
        If zhiding.Checked Then
            withorheight.Enabled = True
            isgrow.Checked = False
            zhidingtype.Enabled = True
        ElseIf isgrow.Checked = False Then
            withorheight.Enabled = False
            zhidingtype.Enabled = False
        Else
            zhidingtype.Enabled = False
        End If
    End Sub

    Private Sub ListView1_DragEnter(sender As Object, e As DragEventArgs) Handles ListView1.DragEnter
        If e.Data.GetDataPresent(DataFormats.FileDrop) Then
            e.Effect = DragDropEffects.Link
        Else
            e.Effect = DragDropEffects.None
        End If
    End Sub

    Private Sub ListView1_DragDrop(sender As Object, e As DragEventArgs) Handles ListView1.DragDrop
        iii = ListView1.Items.Count + 1
        Try
            For Each filepath In e.Data.GetData(DataFormats.FileDrop)
                If File.Exists(filepath) Then
                    Console.WriteLine(filepath)
                    Dim mFileInfo As New System.IO.FileInfo(filepath)
                    Dim ext = mFileInfo.Extension
                    Dim imgWidth As Integer
                    Dim imgHeight As Integer
                    Dim imglenth As String
                    If ext.ToLower = ".png" Or ext.ToLower = ".bmp" Or ext.ToLower = ".jpg" Or ext.ToLower = ".gif" Or ext.ToLower = ".jpeg" Or ext.ToLower = ".webp" Then
                        If alloldpath.Contains(mFileInfo.FullName) = False Then
                            alloldpath.Add(mFileInfo.FullName)
                            Dim imgPhoto As System.Drawing.Image = Imgresize(mFileInfo.FullName, 0, 0)
                            If imgPhoto IsNot Nothing Then
                                imgWidth = imgPhoto.Width
                                imgHeight = imgPhoto.Height
                                imgPhoto.Dispose()
                                imglenth = nFormatFileSize(mFileInfo.Length)
                                Dim itm As ListViewItem = ListView1.Items.Add(iii)
                                itm.SubItems.AddRange({CStr(mFileInfo.Name), CStr(mFileInfo.FullName), imglenth, CStr(imgWidth & " X " & imgHeight), CStr("未处理"), CStr("未处理"), CStr("未处理"), "", "", CStr(mFileInfo.LastWriteTime)})
                                iii = iii + 1
                                Dim t As New TaskList8
                                t.filename = mFileInfo.Name
                                t.imgpath = mFileInfo.FullName
                                t.imgfilesize = imglenth
                                t.imgsize = imgWidth & " X " & imgHeight
                                t.imgsizestate = "未处理"
                                t.koutustate = "未处理"
                                t.fanyistate = "未处理"
                                t.lastedittime = mFileInfo.LastWriteTime
                                t.Add()
                            End If
                        End If
                    End If
                End If
            Next
        Catch ex As Exception

        End Try
    End Sub

    Private Sub Button1_MouseEnter(sender As Object, e As EventArgs) Handles Button1.MouseEnter
        ToolTip1.SetToolTip(Button1, "支持文件夹拖放导入")
    End Sub

    Private Sub imgpath_MouseEnter(sender As Object, e As EventArgs) Handles imgpath.MouseEnter
        ToolTip1.SetToolTip(imgpath, "支持文件夹拖放导入")
    End Sub

    Private Sub jump1_Click(sender As Object, e As EventArgs) Handles jump1.Click
        Try
            Dim lstvid = ListView1.SelectedItems(0).Index
            Dim RequestId = ListView1.SelectedItems(0).SubItems(9).Text
            'Dim outpaths = ListView1.SelectedItems(0).SubItems(9).Text
            Console.WriteLine(lstvid)
            Console.WriteLine(RequestId)

            If RequestId <> "Null" Then
                Dim url = "http://www.waimaomail.com/xt2.php?lstvid=" & lstvid & "&RequestId=" & RequestId

                InvokEx(Sub()
                            Dim frm = New Frm_imgtool()
                            frm.ShowDialog(Me, url)
                        End Sub)
            Else
                MsgBox("请先翻译后处理")
            End If
        Catch ex As Exception

        End Try
    End Sub

    Private Sub jump2_Click(sender As Object, e As EventArgs) Handles jump2.Click
        Try
            Dim lstvid = ListView1.SelectedItems(0).Index
            Dim RequestId = ListView1.SelectedItems(0).SubItems(8).Text
            'Dim outpaths = ListView1.SelectedItems(0).SubItems(9).Text
            Console.WriteLine(lstvid)
            Console.WriteLine(RequestId)

            If RequestId <> "Null" Then
                Dim url = "http://www.waimaomail.com/xt.php?lstvid=" & lstvid & "&RequestId=" & RequestId

                InvokEx(Sub()
                            Dim frm = New Frm_imgtool()
                            frm.ShowDialog(Me, url)
                        End Sub)
            Else
                MsgBox("请先翻译后处理")
            End If
        Catch ex As Exception

        End Try
    End Sub
End Class